package com.first.nell.components.dialog

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.first.nell.ProjectApplication
import com.first.nell.R
import com.first.nell.base.BaseDialogAction
import com.first.nell.databinding.DialogFirstNellCityPickerVndBinding
import org.json.JSONArray
import org.json.JSONObject
import java.nio.charset.Charset

class VndCityPickerDialog : DialogFragment(), BaseDialogAction {

    companion object {
        fun generateFirstNellDialog(title: String?): VndCityPickerDialog {
            val dialog = VndCityPickerDialog()
            dialog.mFirstNellTitle = title
            return dialog
        }
    }

    private lateinit var mFirstNellViewFirstNellBinding: DialogFirstNellCityPickerVndBinding
    private lateinit var mPopListAdapter: PopListAdapter

    var mFirstNellState: String = ""
    var mFirstNellCity: String = ""
    var mFirstNellPickFirstNellType: Int = 0
    var mFirstNellUIFirstNellTag: String = ""

    private var mFirstNellOnFirstNellActionFirstNellListener: (String, Int, PopListItem, Int) -> Unit =
        { uTag, pickTpe, listItem, index -> }
    private var mFirstNellOnFirstNellCompletedFirstNellListener: (String, String, String) -> Unit =
        { uTage, state, city -> }
    private val mFirstNellDataFirstNellList =
        mutableListOf<PopListItem>() as ArrayList<PopListItem>
    private var mFirstNellTitle: String? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE);

        mFirstNellViewFirstNellBinding = DialogFirstNellCityPickerVndBinding.inflate(layoutInflater)
        return mFirstNellViewFirstNellBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initFirstNellSubviews()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }
        mFirstNellViewFirstNellBinding.textDialogCityTitle.text = mFirstNellTitle

        //默认为
        setFirstNellDataFirstNellList(
            0,
            getFirstNellStateFirstNellListFirstNellVnd()
        )

        mPopListAdapter.notifyDataSetChanged()
    }

    override fun initFirstNellSubviews() {

        //初始化城市列表
        initFirstNellCityFirstNellFileFirstNellDataFirstNellVnd()

        mPopListAdapter =
            PopListAdapter(mFirstNellDataFirstNellList)

        mFirstNellViewFirstNellBinding.rcDialogCityList.layoutManager =
            LinearLayoutManager(context)
        mFirstNellViewFirstNellBinding.rcDialogCityList.adapter =
            mPopListAdapter

        mFirstNellViewFirstNellBinding.textDialogCityPickerState.text = mFirstNellState
        mFirstNellViewFirstNellBinding.textDialogCityPickerCity.text = mFirstNellCity

        if (mFirstNellState.isBlank()) {
            mFirstNellViewFirstNellBinding.rlDialogCityPickerResultBg.visibility = View.GONE
        } else {
            mFirstNellViewFirstNellBinding.rlDialogCityPickerResultBg.visibility = View.VISIBLE
        }

        mFirstNellViewFirstNellBinding.textDialogCityPickerState.setOnClickListener {
            mFirstNellPickFirstNellType = R.integer.PickerTypeState
            mFirstNellState = ""
            mFirstNellCity = ""
            mFirstNellViewFirstNellBinding.textDialogCityPickerState.text = mFirstNellState
            mFirstNellViewFirstNellBinding.textDialogCityPickerCity.text = mFirstNellCity
            mFirstNellViewFirstNellBinding.rlDialogCityPickerResultBg.visibility = View.GONE
            mFirstNellOnFirstNellActionFirstNellListener.invoke(
                mFirstNellUIFirstNellTag,
                R.integer.PickerTypeStateReload,
                PopListItem(mFirstNellState, mFirstNellState),
                -1
            )
        }

        mFirstNellViewFirstNellBinding.textDialogCityPickerCity.setOnClickListener {
            mFirstNellPickFirstNellType = R.integer.PickerTypeCity
            mFirstNellViewFirstNellBinding.textDialogCityPickerState.text = mFirstNellState
            mFirstNellViewFirstNellBinding.textDialogCityPickerCity.text = mFirstNellCity
            mFirstNellViewFirstNellBinding.rlDialogCityPickerResultBg.visibility = View.VISIBLE
            mFirstNellOnFirstNellActionFirstNellListener.invoke(
                mFirstNellUIFirstNellTag,
                R.integer.PickerTypeCityReload,
                PopListItem(mFirstNellCity, mFirstNellCity),
                -1
            )
        }

        mPopListAdapter.setFirstNellOnFirstNellItemFirstNellClickFirstNellListener { i, dialogListItem ->
            if (mFirstNellPickFirstNellType == 0) {
                mFirstNellState = dialogListItem.display
                mFirstNellCity = ""
                mFirstNellViewFirstNellBinding.rlDialogCityPickerResultBg.visibility = View.VISIBLE
                mFirstNellViewFirstNellBinding.textDialogCityPickerState.text = mFirstNellState
                mFirstNellViewFirstNellBinding.textDialogCityPickerCity.text = mFirstNellCity
                setFirstNellDataFirstNellList(
                    1,
                    getFirstNellCityFirstNellListFirstNellVnd(mFirstNellState)
                )

            } else if (mFirstNellPickFirstNellType == 1) {
                mFirstNellCity = dialogListItem.content
                mFirstNellViewFirstNellBinding.textDialogCityPickerCity.text = mFirstNellCity
            }
        }

        mFirstNellViewFirstNellBinding.submitDialogCityPicker.setOnClickListener {
            if (mFirstNellState.isBlank() || mFirstNellCity.isBlank()) {
                Toast.makeText(
                    context,
                    "${getString(R.string.first_nell_please_select)} $mFirstNellTitle",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            mFirstNellOnFirstNellCompletedFirstNellListener.invoke(mFirstNellUIFirstNellTag, mFirstNellState, mFirstNellCity)
            dismiss()
        }
    }

    override fun setFirstNellOnFirstNellActionFirstNellClickFirstNellListener(listener: (Int) -> Unit) {

    }

    override fun showFirstNellWithFirstNellUIFirstNellTag(
        gTag: String,
        fragmentManager: FragmentManager
    ) {
        mFirstNellUIFirstNellTag = gTag
        showNow(fragmentManager, VndCityPickerDialog::class.java.simpleName)
    }

    fun getFirstNellState(): String {
        return mFirstNellState
    }

    fun getFirstNellCity(): String {
        return mFirstNellCity
    }

    fun setFirstNellOnFirstNellDataFirstNellClickFirstNellListener(listener: (String, Int, PopListItem, Int) -> Unit) {
        mFirstNellOnFirstNellActionFirstNellListener = listener
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setFirstNellDataFirstNellList(pickType: Int, itemList: List<PopListItem>) {
        mFirstNellPickFirstNellType = pickType
        mFirstNellDataFirstNellList.clear()
        mFirstNellDataFirstNellList.addAll(itemList)

        if (isVisible) {
            mPopListAdapter.notifyDataSetChanged()
        }
    }

    fun setFirstNellOnFirstNellCompletedFirstNellClickFirstNellListener(listener: (String, String, String) -> Unit) {
        mFirstNellOnFirstNellCompletedFirstNellListener = listener
    }

    //越南地址模块
    /** 州 */
    var mFirstNellStateFirstNellVnd: String = ""

    /** 市 */
    var mFirstNellCityFirstNellVnd: String = ""

    /** 区 */
    var mFirstNellAreaFirstNellVnd: String = ""

    /** 州列表 */
    val mFirstNellStateFirstNellListFirstNellVnd = mutableListOf<PopListItem>()

    /** 市列表 */
    val mFirstNellCityFirstNellListFirstNellVnd = mutableListOf<PopListItem>()

    /** 区列表 */
    val mFirstNellAreaFirstNellListFirstNellVnd = mutableListOf<PopListItem>()

    /** 城市数据 */
    var mFirstNellCityFirstNellJsonFirstNellArrayFirstNellVnd: JSONArray? = null

    /** 初始化城市配置-越南 */
    fun initFirstNellCityFirstNellFileFirstNellDataFirstNellVnd() {
        try {
            mFirstNellStateFirstNellListFirstNellVnd.clear()
            val fileInputStream = ProjectApplication.context.assets.open("veitnam_city_list.json")
            val fileContent: String = fileInputStream.readBytes().toString(Charset.defaultCharset())
            mFirstNellCityFirstNellJsonFirstNellArrayFirstNellVnd = JSONArray(fileContent)
            mFirstNellCityFirstNellJsonFirstNellArrayFirstNellVnd?.let {
                for (stateIndex in 0 until it.length()) {
                    val stateObject = it.get(stateIndex) as JSONObject
                    mFirstNellStateFirstNellListFirstNellVnd.add(
                        PopListItem(
                            stateObject.optString("name"),
                            stateObject.optString("name")
                        )
                    )
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 获取州列表-越南 */
    fun getFirstNellStateFirstNellListFirstNellVnd(): MutableList<PopListItem> {
        if ((mFirstNellCityFirstNellJsonFirstNellArrayFirstNellVnd == null) or mFirstNellStateFirstNellListFirstNellVnd.isEmpty()) {
            initFirstNellCityFirstNellFileFirstNellDataFirstNellVnd()
        }
        return mFirstNellStateFirstNellListFirstNellVnd
    }

    /** 获取市列表-越南 */
    fun getFirstNellCityFirstNellListFirstNellVnd(state: String): MutableList<PopListItem> {
        mFirstNellCityFirstNellListFirstNellVnd.clear()
        try {
            mFirstNellCityFirstNellJsonFirstNellArrayFirstNellVnd?.let {
                for (index in 0 until it.length()) {
                    val stateObject = it.get(index) as JSONObject
                    val stateName = stateObject.optString("name")
                    if (state.equals(stateName, false)) {
                        val cityChildren = stateObject.optJSONArray("children")
                        cityChildren?.let { cityArray ->
                            for (cityIndex in 0 until cityArray.length()) {
                                val cityObject = cityArray.get(cityIndex) as JSONObject
                                mFirstNellCityFirstNellListFirstNellVnd.add(
                                    PopListItem(
                                        cityObject.optString("name"),
                                        cityObject.optString("name")
                                    )
                                )
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mFirstNellCityFirstNellListFirstNellVnd
    }

    /** 获取区列表-越南 */
    fun getFirstNellAreaFirstNellListFirstNellVnd(
        state: String,
        city: String
    ): MutableList<PopListItem> {
        mFirstNellAreaFirstNellListFirstNellVnd.clear()
        try {
            mFirstNellCityFirstNellJsonFirstNellArrayFirstNellVnd?.let {
                for (stateIndex in 0 until it.length()) {
                    val jsonObject = it.get(stateIndex) as JSONObject
                    val stateName = jsonObject.optString("name")
                    //查state
                    if (state.equals(stateName, false)) {
                        val cityChildren = jsonObject.optJSONArray("children")
                        cityChildren?.let { cityArray ->
                            for (cityIndex in 0 until cityArray.length()) {
                                val cityObject = cityArray.get(cityIndex) as JSONObject
                                val cityName = cityObject.optString("name")
                                //查city
                                if (city.equals(cityName, false)) {
                                    val townChildren = cityObject.optJSONArray("children")
                                    //查town
                                    townChildren?.let { townArray ->
                                        for (townIndex in 0 until townArray.length()) {
                                            val townObject = townArray.get(townIndex) as JSONObject
                                            mFirstNellAreaFirstNellListFirstNellVnd.add(
                                                PopListItem(
                                                    townObject.optString("name"),
                                                    townObject.optString("name")
                                                )
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mFirstNellAreaFirstNellListFirstNellVnd
    }
}